package middleware

import (
	"blogx_server/common/res"
	"blogx_server/models/enum"
	"blogx_server/service/log_service"
	"github.com/gin-gonic/gin"
)

func BindQueryMiddleware[T any](c *gin.Context) {
	log := log_service.GetLog(c)
	log.ShowRequest()
	log.ShowRequestHeader()
	log.ShowResponse()
	log.ShowResponseHeader()
	var cr T
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		log.SetError("query参数绑定失败", err)
		log.SetLevel(enum.LogErrLevel)
		log.Save()
		res.FailWithError(err, c)
		c.Abort()
		return
	}
	log.Save()
	c.Set("request", cr)
	return
}

func BindJsonMiddleware[T any](c *gin.Context) {
	log := log_service.GetLog(c)
	log.ShowRequest()
	log.ShowRequestHeader()
	log.ShowResponse()
	log.ShowResponseHeader()
	var cr T
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		log.SetError("json参数绑定失败", err)
		log.SetLevel(enum.LogErrLevel)
		log.Save()
		res.FailWithError(err, c)
		c.Abort()
		return
	}

	log.Save()
	c.Set("request", cr)
	return
}

func BindUriMiddleware[T any](c *gin.Context) {
	log := log_service.GetLog(c)
	log.ShowRequest()
	log.ShowRequestHeader()
	log.ShowResponse()
	log.ShowResponseHeader()
	var cr T
	err := c.ShouldBindUri(&cr)
	if err != nil {
		log.SetError("uri参数绑定失败", err)
		log.SetLevel(enum.LogErrLevel)
		log.Save()
		res.FailWithError(err, c)
		c.Abort()
		return
	}
	log.Save()

	c.Set("request", cr)
	return
}

func GetBind[T any](c *gin.Context) (cr T) {
	return c.MustGet("request").(T)
}
